import gi
import socket

gi.require_version('Gst', '1.0')
gi.require_version('GstRtspServer', '1.0')
from gi.repository import Gst, GstRtspServer, GObject

class MyFactory(GstRtspServer.RTSPMediaFactory):
    def __init__(self):
        super(MyFactory, self).__init__()

    def do_create_element(self, url):
        pipeline_str = (
            "videotestsrc ! x264enc ! rtph264pay name=pay0 pt=96"
        )
        return Gst.parse_launch(pipeline_str)

def get_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.254.254.254', 1))
        ip = s.getsockname()[0]
    except Exception:
        ip = '127.0.0.1'
    finally:
        s.close()
    return ip

def main():
    GObject.threads_init()
    Gst.init(None)

    server = GstRtspServer.RTSPServer()
    local_ip = get_local_ip()
    server.set_address(local_ip)

    factory = MyFactory()
    factory.set_shared(True)

    mount_points = server.get_mount_points()
    mount_points.add_factory("/test", factory)

    server.attach(None)
    print(f"RTSP server is running at rtsp://{local_ip}:8554/test")
    loop = GObject.MainLoop()
    loop.run()

if __name__ == "__main__":
    main()